package org.scohen.juploadr.uploadapi.zooomr;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.scohen.juploadr.app.ImageAttributes;
import org.scohen.juploadr.app.PhotoSet;
import org.scohen.juploadr.ui.Task;
import org.scohen.juploadr.uploadapi.zooomr.photosets.AddPhoto;

public class AddToPhotosetTask extends Task {
    private Collection sets;
    private ZooomrRestApi api;
    private int numberOfSets;
    private boolean hasSetsToAdd;
    private String currentPhoto;
    private String currentSet;
    private int current = 0;

    public AddToPhotosetTask(Collection photoSets, ZooomrRestApi api) {
        this.sets = photoSets;
        this.api = api;
        this.min = 0;
        this.max = getTotalNumberOfPhotosToAdd(photoSets);
        hasSetsToAdd = this.max != 0;
    }

    public String getTitle() {
        return Messages
                .getString("juploadr.zooomr.task.addtophotoset.adding") + max + Messages.getString("juploadr.flickrrest.task.addtophotoset.photos"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    public void execute() {
        // now add the photos in the set
        Iterator iter = sets.iterator();
        while (iter.hasNext()) {
            PhotoSet set = (PhotoSet) iter.next();
            currentSet = set.getTitle();
            List photos = set.getPhotos();
            Iterator photoIter = photos.iterator();
            while (photoIter.hasNext()) {
                ImageAttributes thumb = (ImageAttributes) photoIter.next();
                currentPhoto = thumb.getTitle();
                updateProgress(++current);
                if (!thumb.getPhotoId().equals(set.getPrimaryPhotoId())) {
                    AddPhoto add = new AddPhoto(set, thumb);
                    if (api.executeMethod(add)) {

                    }

                }

            }
        }
    }

    private int getTotalNumberOfPhotosToAdd(Collection sets) {
        Iterator iter = sets.iterator();
        int count = 0;
        while (iter.hasNext()) {
            PhotoSet set = (PhotoSet) iter.next();
            if (set.getPhotos().size() > 0) {
                numberOfSets++;
                count += set.getPhotos().size();
            }
        }
        return count;
    }

    public String getMessage() {
        return ((max - current) + 1)
                + Messages
                        .getString("juploadr.zooomr.task.addtophotoset.photostoaddto") + numberOfSets //$NON-NLS-1$
                + Messages
                        .getString("juploadr.zooomr.task.addtophotoset.sets") + Messages.getString("juploadr.flickrrest.task.addtophotoset.photosets") + Messages.getString("juploadr.flickrrest.task.addtophotoset.adding") + currentPhoto //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                + Messages
                        .getString("juploadr.zooomr.task.addtophotoset.to") + currentSet; //$NON-NLS-1$
    }

    public boolean hasSetsToAdd() {
        return hasSetsToAdd;
    }

}
